package logic

import (
	"cloud-disk/global/db"
	"cloud-disk/global/define"
	"cloud-disk/model/entity"
	"cloud-disk/model/request"
	"cloud-disk/util"
	"errors"
	"fmt"
	"log"
)

// UserLoginLogic 用户登录
func UserLoginLogic(login request.Login) (*entity.User, error) {
	var user entity.User
	err := db.DB().Where("email=? and password=?", login.Email, util.Sha1Crypt([]byte(login.Password))).Find(&user).Error
	if err != nil {
		log.Println(err)
		return nil, err
	}
	ok, err := validCaptcha(login.Email, login.Captcha)
	if !ok {
		log.Println(err)
		return nil, err
	}
	return &user, nil
}

// UserInfoLogic 用户信息
func UserInfoLogic(id int) (*entity.User, error) {
	var user entity.User
	err := db.DB().Where("id=?", id).Find(&user).Error
	fmt.Println(user)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	return &user, nil
}

// UserSendCaptchaLogic 用户请求验证码
func UserSendCaptchaLogic(email, mode string) error {
	exist, err := IsRegisteredLogic(email)
	if err != nil {
		return err
	}
	if mode == "login" && !exist {
		return errors.New("no account")
	}
	if mode == "register" && exist {
		return errors.New("account exist")
	}
	code := util.Captcha(6)
	// redis
	{
		c := db.RDB().Get()
		defer c.Close()
		c.Send("SET", email, code)
		c.Send("EXPIRE", email, define.Conf.Captcha.Expire)
		c.Flush()
		_, err = c.Receive()
	}
	if err != nil {
		log.Println(err)
		return errors.New("unknown error")
	}
	return nil
}

// IsRegisteredLogic 查看是否已注册
func IsRegisteredLogic(email string) (bool, error) {
	var cnt int64
	err := db.DB().Model(&entity.User{}).Where("email=?", email).Count(&cnt).Error
	if err != nil {
		log.Println(err)
		return true, errors.New("unknown error")
	}
	if cnt > 0 {
		return true, nil
	}
	return false, nil
}

// UserRegisterLogic 用户注册
func UserRegisterLogic(req request.Register) error {
	user := entity.User{
		Identity: util.UUID(),
		Name:     req.Name,
		Password: util.Sha1Crypt([]byte(req.Password)),
		Email:    req.Email,
		Phone:    req.Phone,
	}
	//
	ok, err := validCaptcha(req.Email, req.Captcha)
	if !ok {
		log.Println(err)
		return err
	}
	// 执行用户插入
	res := db.DB().Create(&user)
	err = res.Error
	affect := res.RowsAffected
	if err != nil {
		log.Println("insert error")
		return errors.New("register unknown error")
	}
	if affect <= 0 {
		errors.New("user exist")
	}
	return nil
}

// validCaptcha 校验验证码
func validCaptcha(email, captcha string) (bool, error) {
	// 获取redis连接
	c := db.RDB().Get()
	defer c.Close()
	// 从redis获取验证码
	ans, err := c.Do("GET", email)
	if ans == nil || err != nil {
		log.Println(err)
		return false, errors.New("captcha overtime")
	}
	// 验证是否相同
	data := ans.([]byte)
	if string(data) != captcha {
		return false, errors.New("captcha unmatched")
	}
	// 用完就删除
	c.Do("DEL", email)
	return true, nil
}
